﻿//JumbotCms_4.1 Final
using System;
using System.Data;
using System.Web;
using Jumbot.Common;
namespace JumbotCms.Extends.Comment
{
    public partial class _ajax : JumbotCms.API.AdminCenter
    {
        private string _operType = string.Empty;
        private string _response = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            Server.ScriptTimeout = 8;//脚本过期时间
            this._operType = q("oper");
            switch (this._operType)
            {
                case "ajaxGetList":
                    ajaxGetList();
                    break;
                case "ajaxBatchOper":
                    ajaxBatchOper();
                    break;
                case "ajaxPluginComment":
                    GetComment();
                    break;
                case "ajaxPluginCommentCount":
                    GetCommentCount();
                    break;
                case "ajaxPluginCommentAdd":
                    GetCommentAdd();
                    break;
                case "ajaxPluginCommentList":
                    GetCommentList();
                    break;
                case "ajaxPluginCommentTopList":
                    GetCommentTopList();
                    break;
                case "ajaxPluginCommentUserInfo":
                    GetUserInfo();
                    break;
                default:
                    DefaultResponse();
                    break;
            }

            Response.Write(this._response);
        }

        private void DefaultResponse()
        {
            this._response = "{result :\"未知操作\"}";
        }
        private void ajaxGetList()
        {
            Admin_Load("0000", "json");
            string ccid = Str2Str(q("ccid"));
            string id = Str2Str(q("id"));
            int PSize = Str2Int(q("pagesize"), 0) == 0 ? 15 : Str2Int(q("pagesize"), 0);
            int page = Int_ThisPage();
            string sqlStr = "";
            int countNum = 0;
            string whereStr = "[ParentId]=0";
            if (id != "0") whereStr += " AND [ContentId]=" + id;
            if (ccid != "0") whereStr += " AND [ChannelId]=" + ccid;
            doh.Reset();
            doh.ConditionExpress = whereStr;
            countNum = doh.Count("jcms_extends_comment");
            sqlStr = Jumbot.Common.staticFunction.GetSql("Id,IP,UserName,AddDate,Content,IsPass", "jcms_extends_comment", "id", PSize, page, "desc", whereStr);
            doh.Reset();
            doh.SqlCmd = sqlStr;
            DataTable dt = doh.GetDataTable();
            this._response = "{result :\"1\"," +
                "returnval :\"操作成功\"," +
                "pagerbar :\"" + Jumbot.Common.HtmlPager.GetPageBar(3, "js", 2, countNum, PSize, page, "javascript:ajaxList(<#page#>);") + "\"," +
                Jumbot.Common.JsonHelp.DtToSON(dt) +
                "}";
            dt.Clear();
            dt.Dispose();
        }
        /// <summary>
        /// 执行批量操作
        /// </summary>
        /// <param name="oper"></param>
        /// <param name="ids"></param>
        private void ajaxBatchOper()
        {
            Admin_Load("0000", "json");
            string act = q("act");
            string ids = f("ids");
            string[] idValue;
            idValue = ids.Split(',');
            string ClassId = string.Empty;
            if (act == "pass")
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    doh.AddFieldItem("IsPass", 1);
                    doh.Update("jcms_extends_comment");
                }
            }
            else if (act == "nopass")
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    doh.AddFieldItem("IsPass", 0);
                    doh.Update("jcms_extends_comment");
                }
            }
            else//均为删除
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "id=@id";
                    doh.AddConditionParameter("@id", idValue[i]);
                    doh.Delete("jcms_extends_comment");
                    doh.Reset();
                    doh.ConditionExpress = "ParentId=" + idValue[i];
                    doh.Delete("jcms_extends_comment");
                }
            }
            this._response = JsonResult(1, "操作成功");
        }
        private void GetComment()
        {
            this._response = "{channelid :\"" + q("ccid") + "\",contentid:" + q("id") + "}";
        }
        private void GetCommentCount()
        {

            doh.ConditionExpress = "contentid=" + q("id") + " and channelid=" + q("ccid");
            if (!doh.Exist("jcms_extends_comment"))
            {
                doh.Reset();
                doh.AddFieldItem("ContentId", q("id"));
                doh.AddFieldItem("ChannelId", q("ccid"));
                doh.AddFieldItem("CommentNum", 0);
                doh.Insert("jcms_extends_comment");
            }
            doh.Reset();
            doh.ConditionExpress = "contentid=" + q("id") + " and channelid=" + q("ccid");
            this._response = "{count :\"" + Validator.IntStr(doh.GetValue("jcms_extends_comment", "CommentNum").ToString()) + "\"}";
        }
        private void GetCommentAdd()
        {
            string uName, pId;
            pId = f("parentid");
            string _code = f("code");
            int _GuestPost = Jumbot.Common.Validator.StrToInt(Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "_data/config/extends_comment", "GuestPost"), 0);
            int _NeedCheck = Jumbot.Common.Validator.StrToInt(Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "_data/config/extends_comment", "NeedCheck"), 0);
            int _PostTimer = Jumbot.Common.Validator.StrToInt(Jumbot.Common.XmlCOM.ReadConfig(site.Dir + "_data/config/extends_comment", "PostTimer"), 0);
            int _State;
            if (Cookie.GetValue(site.CookiePrev + "user") == null)//判断游客权限
            {
                if (_GuestPost == 0)
                {
                    this._response = "请登录后再进行评论";
                    return;
                }
            }
            if (Cookie.GetValue("ValidateCode") != _code)
            {
                this._response = "验证码错误";
                return;
            }
            bool IsMaster = false;
            if (Cookie.GetValue(site.CookiePrev + "admin") != null)
            {
                uName = Cookie.GetValue(site.CookiePrev + "user", "name");
                _State = 1;
                IsMaster = true;
            }
            else
            {
                if (pId != "0")
                {
                    this._response = "管理员登录后才可回复评论!";
                    return;
                }
                if (Cookie.GetValue(site.CookiePrev + "user") != null)
                {
                    uName = Cookie.GetValue(site.CookiePrev + "user", "name");
                    _State = (_NeedCheck == 0) ? 1 : 0;
                }
                else
                {
                    uName = Jumbot.Common.Strings.HtmlEncode(f("name")).Replace("[", "").Replace("]", "");
                    _State = (_NeedCheck == 0) ? 1 : 0;
                }
            }
            if (!Jumbot.Common.Validator.IsNumeric(f("ccid")))
            {
                this._response = "频道有误!";
                return;
            }
            if (!Jumbot.Common.Validator.IsNumeric(f("id")))
            {
                this._response = "ID有误!";
                return;
            }

            if (IsMaster == false && Jumbot.Common.Cookie.GetValue("contentComment" + f("id")) != null)
            {
                this._response = "请不要频繁评论!";
                return;
            }
            if (IsMaster == false)
            {
                int countNum = 0;
                string whereStr = "[ParentId]=0 AND [IP]='" + GetUserIp() + "'";
                if (DBType == "0")
                    whereStr += " and datediff('s',adddate,'" + DateTime.Now.ToString() + "')<" + _PostTimer;
                else
                    whereStr += " and datediff(s,adddate,'" + DateTime.Now.ToString() + "')<" + _PostTimer;
                doh.Reset();
                doh.ConditionExpress = whereStr;
                countNum = doh.Count("jcms_extends_comment");
                if (countNum > 0)//说明周期内评论过
                {
                    this._response = _PostTimer + "秒内只能评论一次!";
                    return;
                }
            }
            doh.Reset();
            doh.AddFieldItem("ChannelId", f("ccid"));
            doh.AddFieldItem("ParentId", pId);
            doh.AddFieldItem("ContentId", f("id"));
            doh.AddFieldItem("AddDate", DateTime.Now.ToString());
            doh.AddFieldItem("Content", GetCutString(Jumbot.Common.Strings.HtmlEncode(f("content")), 200));
            doh.AddFieldItem("IP", GetUserIp());
            doh.AddFieldItem("UserName", uName);
            doh.AddFieldItem("IsPass", _State);
            doh.Insert("jcms_extends_comment");
            this._response = "ok";
        }
        private void GetCommentList()
        {
            string ccid = Str2Str(q("ccid"));
            string id = Str2Str(q("id"));
            if (!Jumbot.Common.Validator.IsNumeric(id))
            {
                this._response = "ID有误!";
                return;
            }
            int PSize = Str2Int(q("pagesize"), 0) == 0 ? 5 : Str2Int(q("pagesize"), 0);
            int page = Int_ThisPage();
            string LoopBody = string.Empty;
            string ViewStr = string.Empty;
            string ReplaceStr = string.Empty;
            string ViewReplyStr = string.Empty;
            string ReplaceReplyStr = string.Empty;
            string ReplyBody = string.Empty;
            ViewStr = Jumbot.Common.DirFile.ReadFile(site.Dir + "extends/comment/templates/_body.htm");
            LoopBody = ViewStr;
            ViewReplyStr = Jumbot.Common.DirFile.ReadFile(site.Dir + "extends/comment/templates/_replybody.htm");
            ReplyBody = ViewReplyStr;
            string sqlStr = "";
            int countNum = 0;
            string whereStr = " [ParentId]=0 AND [ContentId]=" + id + " AND [ChannelId]=" + ccid;
            doh.Reset();
            //doh.SqlCmd = "SELECT count(id) AS CC FROM [jcms_extends_comment] WHERE " + whereStr;
            //countNum = Jumbot.Common.Validator.StrToInt(doh.GetDataTable().Rows[0]["cc"].ToString(), 0);
            doh.ConditionExpress = whereStr;
            countNum = doh.Count("jcms_extends_comment");

            sqlStr = Jumbot.Common.staticFunction.GetSql("Id,IP,UserName,AddDate,Content", "jcms_extends_comment", "id", PSize, page, "desc", whereStr);
            doh.Reset();
            doh.SqlCmd = sqlStr;
            DataTable dtComment = doh.GetDataTable();

            for (int j = 0; j < dtComment.Rows.Count; j++)
            {
                ViewStr = LoopBody;
                for (int i = 0; i < dtComment.Columns.Count; i++)
                {
                    ViewStr = ViewStr.Replace("{$Comment" + dtComment.Columns[i].ColumnName + "}", dtComment.Rows[j][i].ToString());
                }
                doh.Reset();
                doh.SqlCmd = "SELECT Id,IP,UserName,AddDate,Content FROM [jcms_extends_comment] WHERE [ParentId]=" + dtComment.Rows[j]["Id"].ToString() + " AND [ContentId]=" + id + " AND [ChannelId]=" + ccid;
                DataTable dtCommentReply = doh.GetDataTable();
                if (dtCommentReply.Rows.Count > 0)
                {
                    ViewReplyStr = ReplyBody;
                    for (int k = 0; k < dtCommentReply.Columns.Count; k++)
                    {
                        ViewReplyStr = ViewReplyStr.Replace("{$CommentReply" + dtCommentReply.Columns[k].ColumnName + "}", dtCommentReply.Rows[0][k].ToString());
                    }
                    ViewStr = ViewStr.Replace("{$CommentReplyBody}", ViewReplyStr);
                }
                else
                {
                    if (Cookie.GetValue(site.CookiePrev + "admin") != null)
                        ViewStr = ViewStr.Replace("{$CommentReplyBody}", "<br /><span onclick=\"ajaxPluginCommentReply2(" + dtComment.Rows[j]["Id"].ToString() + ");\" style=\"cursor:pointer;float:right;margin-right:10px;color:#669933;\">回复该评论</span>");
                    else
                        ViewStr = ViewStr.Replace("{$CommentReplyBody}", "");
                }
                dtCommentReply.Clear();
                dtCommentReply.Dispose();
                ReplaceStr += ViewStr;
            }
            dtComment.Clear();
            dtComment.Dispose();
            ReplaceStr += "<div class=\"pages\">" + Jumbot.Common.HtmlPager.GetPageBar(3, "js", 2, countNum, PSize, page, "javascript:ajaxPluginCommentList(" + ccid + "," + id + ",<#page#>);") + "</div>";

            this._response = ReplaceStr;

        }
        private void GetCommentTopList()
        {
            string ccid = Str2Str(q("ccid"));
            string id = Str2Str(q("id"));
            if (!Jumbot.Common.Validator.IsNumeric(id))
            {
                this._response = "ID有误!";
                return;
            }
            int PSize = Str2Int(q("pagesize"), 0) == 0 ? 5 : Str2Int(q("pagesize"), 0);
            int page = Int_ThisPage();
            string sqlStr = "";
            int countNum = 0;
            string whereStr = " [ParentId]=0";
            if (ccid != "0") whereStr += " AND [ChannelId]=" + ccid;
            if (id != "0") whereStr += " AND [ContentId]=" + id;
            doh.Reset();
            doh.ConditionExpress = whereStr;
            countNum = doh.Count("jcms_extends_comment");

            sqlStr = Jumbot.Common.staticFunction.GetSql("Id,ChannelId,ContentId,IP,UserName,AddDate,Content", "jcms_extends_comment", "id", PSize, page, "desc", whereStr);
            doh.Reset();
            doh.SqlCmd = sqlStr;
            DataTable dtComment = doh.GetDataTable();
            string ResponseStr = "<ul>";
            for (int j = 0; j < dtComment.Rows.Count; j++)
            {
                ResponseStr += "<li><a href=\"" + Go2View(doh, 1, false, dtComment.Rows[j]["ChannelId"].ToString(), dtComment.Rows[j]["ContentId"].ToString()) + "\" target=\"_blank\">" + dtComment.Rows[j]["Content"].ToString() + "</a></li>";
            }
            ResponseStr += "</ul>";
            dtComment.Clear();
            dtComment.Dispose();
            this._response = ResponseStr;

        }
        private void GetUserInfo()
        {
            if (Cookie.GetValue(site.CookiePrev + "user") != null)
            {
                this._response = "{username :\"" + Cookie.GetValue(site.CookiePrev + "user", "name") + "\"}";
            }
            else
            {
                this._response = "{username :\"\"}";
            }
        }
    }
}
